package com.ruoyi.web.controller.tool;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.vo.SocialUser;
import com.ruoyi.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;



/**
 * @author he_jiebing@jiuyv.com
 * @create 2024-04-19 10:21
 */

@Controller
public class OAuth2Controller {
    protected Logger LOG = LoggerFactory.getLogger(getClass());

    @Autowired
    private ISysUserService userService;

    @Autowired
    private RedisCache redisCache;
    @GetMapping("/success")
    public String weibo(@RequestParam("code") String code,  HttpServletResponse response){
        // 1、根据code换取accessToken
        LOG.info(">>>>>>>>>>>>code>>{}",code);
        String url = "https://api.weibo.com/oauth2/access_token";
        Map<String,Object> param = new HashMap<>();
        param.put("client_id","3434294229");
        param.put("client_secret","ec91d20955c9f1a25f0f4cb6b29a1896");
        param.put("grant_type","authorization_code");
        param.put("code",code);
        param.put("redirect_uri","http://www.freeze721.com:8080/success");
        LOG.info(">>>>>>>>>>>>url>>{},param>>{}",url,JSONUtil.toJsonStr(param));
        String result = HttpUtil.post(url, param);
        LOG.info(">>>>>>>>>>>>>result>>{}",result);
        SocialUser socialUser = JSONUtil.toBean(result, SocialUser.class);
        String uid = socialUser.getUid();
        SysUser sysUser = userService.selectUserBySocialUid(uid);
        if(null == sysUser){
            SysUser newUser = new SysUser();
            newUser.setSocialUid(uid);
            newUser.setAccessToken(socialUser.getAccess_token());
            newUser.setExpiresIn(socialUser.getExpires_in());
            Map<String,Object> reqParam = new HashMap<>();
            reqParam.put("access_token",socialUser.getAccess_token());
            reqParam.put("uid",uid);
            String reqUserUrl = "https://api.weibo.com/2/users/show.json";
            LOG.info(">>>>>>>>>>>>url>>{},param>>{}",reqUserUrl,JSONUtil.toJsonStr(reqParam));
            String userResult = HttpUtil.get(reqUserUrl, reqParam);
            LOG.info(">>>>>>>>>>>>>userResult>>{}",userResult);
            JSONObject jsonObject = JSONUtil.parseObj(userResult);
            String name = jsonObject.getStr("name");
            String avatar = jsonObject.getStr("avatar_large");
             newUser.setNickName(name);
             newUser.setUserName(name);
             newUser.setAvatar(avatar);
            userService.insertUser(newUser);
        }else{
            //SysUser upateUser = new SysUser();
            sysUser.setAccessToken(socialUser.getAccess_token());
            sysUser.setExpiresIn(socialUser.getExpires_in());
            userService.updateUser(sysUser);
        }

        // 处理微博回调，并生成 token
        // 将 token 存储在 Cookie 中
        Cookie tokenCookie = new Cookie("Admin-Token", socialUser.getAccess_token());
        tokenCookie.setMaxAge(3600); // 设置有效期
        response.addCookie(tokenCookie);

        String key = "weibo_tokens:"+socialUser.getAccess_token();
        LoginUser user = new LoginUser();
        user.setUserId(sysUser.getUserId());
        //user.setDeptId(0L);
        user.setToken(socialUser.getAccess_token());
        //user.setLoginTime(0L);
        //user.setIpaddr("");
        //user.setLoginLocation("");
        //user.setBrowser("");
        //user.setOs("");
        //user.setExpireTime(0L);
        //user.setPermissions(new HashSet<>());
        user.setUser(sysUser);


        redisCache.setCacheObject(key,user);

        // TODO
        // 1)、 当前用户如果是第一次进网站，自动注册进来（为当前社交用户生成一个会员）
        // 2、登录成功就跳回首页
        return "redirect:http://www.freeze721.com/index";

    }
}
